#!/bin/bash

# 重装系统后快速部署脚本 v2.0
# 专为重装Linux系统后的快速持久化测试设计

VERSION="2.0.0"
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SESSION_ID=$(date +%Y%m%d_%H%M%S)

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m'

# 配置参数
INSTALL_PYTHON3=true
INSTALL_DEPENDENCIES=true
AUTO_START_TEST=true
CLEANUP_AFTER_TEST=false

# 显示横幅
show_banner() {
    clear
    cat << 'EOF'
╔══════════════════════════════════════════════════════════════════════╗
║                🚀 重装系统后快速部署脚本 v2.0 🚀                      ║
║                     专为新系统环境优化设计                            ║
╠══════════════════════════════════════════════════════════════════════╣
║  ⚡ 快速安装  |  🔧 环境配置  |  🚀 一键测试  |  📊 即时报告          ║
║  🛡️ 安全检查  |  📋 系统适配  |  🧹 自动清理  |  ✅ 100%自动化        ║
╚══════════════════════════════════════════════════════════════════════╝
EOF
    echo
    echo -e "${CYAN}🆔 版本: $VERSION${NC}"
    echo -e "${CYAN}📅 时间: $(date '+%Y-%m-%d %H:%M:%S')${NC}"
    echo -e "${CYAN}🎯 会话: $SESSION_ID${NC}"
    echo "=" * 70
}

# 日志函数
log_info() {
    echo -e "${BLUE}[*]${NC} $1"
}

log_success() {
    echo -e "${GREEN}[+]${NC} $1"
}

log_warning() {
    echo -e "${YELLOW}[!]${NC} $1"
}

log_error() {
    echo -e "${RED}[-]${NC} $1"
}

log_step() {
    echo -e "${PURPLE}[>]${NC} $1"
}

# 检测系统类型
detect_system() {
    log_info "检测系统环境..."
    
    # 检测发行版
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        DISTRO=$ID
        VERSION_ID=$VERSION_ID
    else
        DISTRO="unknown"
        VERSION_ID="unknown"
    fi
    
    # 检测包管理器
    if command -v apt &> /dev/null; then
        PKG_MANAGER="apt"
        PKG_UPDATE="apt update"
        PKG_INSTALL="apt install -y"
    elif command -v yum &> /dev/null; then
        PKG_MANAGER="yum"
        PKG_UPDATE="yum update -y"
        PKG_INSTALL="yum install -y"
    elif command -v dnf &> /dev/null; then
        PKG_MANAGER="dnf"
        PKG_UPDATE="dnf update -y"
        PKG_INSTALL="dnf install -y"
    elif command -v zypper &> /dev/null; then
        PKG_MANAGER="zypper"
        PKG_UPDATE="zypper refresh"
        PKG_INSTALL="zypper install -y"
    else
        PKG_MANAGER="unknown"
    fi
    
    log_success "系统检测完成:"
    echo "  发行版: $DISTRO $VERSION_ID"
    echo "  包管理器: $PKG_MANAGER"
    echo "  架构: $(uname -m)"
    echo "  内核: $(uname -r)"
    echo
}

# 检查Root权限
check_root() {
    if [ $EUID -ne 0 ]; then
        log_error "需要Root权限运行此脚本"
        log_error "请使用: sudo bash $0"
        exit 1
    fi
    log_success "Root权限验证通过"
}

# 系统初始化检查
system_initialization_check() {
    log_step "执行系统初始化检查..."
    
    # 检查网络连接
    log_info "检查网络连接..."
    if ping -c 3 8.8.8.8 &> /dev/null; then
        log_success "网络连接正常"
    else
        log_warning "网络连接异常，可能影响软件包安装"
    fi
    
    # 检查磁盘空间
    log_info "检查磁盘空间..."
    available_space=$(df / | awk 'NR==2 {print $4}')
    if [ "$available_space" -gt 1048576 ]; then  # 1GB
        log_success "磁盘空间充足 ($(($available_space/1024/1024))GB 可用)"
    else
        log_warning "磁盘空间不足，建议至少保留1GB空间"
    fi
    
    # 检查系统负载
    log_info "检查系统负载..."
    load_avg=$(uptime | awk -F'load average:' '{print $2}' | awk '{print $1}' | sed 's/,//')
    if (( $(echo "$load_avg < 2.0" | bc -l) )); then
        log_success "系统负载正常 ($load_avg)"
    else
        log_warning "系统负载较高 ($load_avg)"
    fi
    
    echo
}

# 安装必要依赖
install_dependencies() {
    log_step "安装必要依赖..."
    
    if [ "$PKG_MANAGER" = "unknown" ]; then
        log_error "未知的包管理器，无法自动安装依赖"
        return 1
    fi
    
    # 更新包列表
    log_info "更新软件包列表..."
    eval $PKG_UPDATE
    
    # 基础依赖包
    BASIC_PACKAGES="python3 python3-pip curl wget git openssh-server cron"
    
    # 根据发行版调整包名
    case $DISTRO in
        "ubuntu"|"debian")
            PACKAGES="$BASIC_PACKAGES systemd bc"
            ;;
        "centos"|"rhel"|"fedora")
            PACKAGES="$BASIC_PACKAGES systemd bc"
            ;;
        "opensuse"|"sles")
            PACKAGES="$BASIC_PACKAGES systemd bc"
            ;;
        *)
            PACKAGES="$BASIC_PACKAGES"
            ;;
    esac
    
    # 安装依赖包
    log_info "安装依赖包: $PACKAGES"
    eval "$PKG_INSTALL $PACKAGES"
    
    if [ $? -eq 0 ]; then
        log_success "依赖包安装完成"
    else
        log_error "依赖包安装失败"
        return 1
    fi
    
    # 启用必要服务
    log_info "启用必要服务..."
    systemctl enable ssh 2>/dev/null || systemctl enable sshd 2>/dev/null || true
    systemctl enable cron 2>/dev/null || systemctl enable crond 2>/dev/null || true
    
    log_success "服务配置完成"
    echo
}

# 配置系统环境
configure_system() {
    log_step "配置系统环境..."
    
    # 创建必要目录
    log_info "创建工作目录..."
    mkdir -p /tmp/persistence_test
    mkdir -p /tmp/persistence_logs
    mkdir -p /tmp/persistence_backup
    mkdir -p /root/.ssh
    
    # 设置SSH目录权限
    chmod 700 /root/.ssh
    touch /root/.ssh/authorized_keys
    chmod 600 /root/.ssh/authorized_keys
    
    # 备份重要配置文件
    log_info "备份重要配置文件..."
    cp /root/.bashrc /tmp/persistence_backup/.bashrc.original 2>/dev/null || true
    cp /etc/crontab /tmp/persistence_backup/crontab.original 2>/dev/null || true
    
    # 确保Python3可用
    if ! command -v python3 &> /dev/null; then
        log_error "Python3 安装失败或不可用"
        return 1
    fi
    
    # 检查Python模块
    log_info "检查Python模块..."
    python3 -c "import json, subprocess, threading, signal" 2>/dev/null
    if [ $? -eq 0 ]; then
        log_success "Python环境配置正确"
    else
        log_warning "Python模块可能不完整"
    fi
    
    log_success "系统环境配置完成"
    echo
}

# 系统安全检查
security_check() {
    log_step "执行系统安全检查..."
    
    # 检查防火墙状态
    log_info "检查防火墙状态..."
    if systemctl is-active firewalld &> /dev/null; then
        log_warning "firewalld 正在运行，可能影响测试"
        echo "  建议: systemctl stop firewalld"
    elif systemctl is-active ufw &> /dev/null; then
        log_warning "ufw 正在运行，可能影响测试"
        echo "  建议: ufw disable"
    else
        log_success "防火墙状态正常"
    fi
    
    # 检查SELinux状态
    if command -v getenforce &> /dev/null; then
        selinux_status=$(getenforce 2>/dev/null || echo "Unknown")
        if [ "$selinux_status" = "Enforcing" ]; then
            log_warning "SELinux 处于强制模式，可能影响测试"
            echo "  建议: setenforce 0"
        else
            log_success "SELinux 状态: $selinux_status"
        fi
    fi
    
    # 检查AppArmor状态
    if command -v aa-status &> /dev/null; then
        if aa-status --enabled &> /dev/null; then
            log_warning "AppArmor 已启用，可能影响测试"
        else
            log_success "AppArmor 状态正常"
        fi
    fi
    
    # 检查运行中的安全软件
    log_info "检查安全软件..."
    security_processes=$(ps aux | grep -E "(antivirus|clamav|rkhunter|chkrootkit)" | grep -v grep || true)
    if [ -n "$security_processes" ]; then
        log_warning "检测到安全软件运行中"
        echo "$security_processes"
    else
        log_success "未检测到冲突的安全软件"
    fi
    
    echo
}

# 运行快速测试
run_quick_test() {
    log_step "运行快速持久化测试..."
    
    PYTHON_SCRIPT="$SCRIPT_DIR/ultimate_persistence_tester.py"
    
    if [ ! -f "$PYTHON_SCRIPT" ]; then
        log_error "测试脚本不存在: $PYTHON_SCRIPT"
        return 1
    fi
    
    log_info "启动终极持久化测试器..."
    echo
    
    # 运行测试
    python3 "$PYTHON_SCRIPT" --test
    
    if [ $? -eq 0 ]; then
        log_success "快速测试完成!"
        
        # 显示测试结果摘要
        show_test_summary
        
        return 0
    else
        log_error "快速测试失败!"
        return 1
    fi
}

# 显示测试结果摘要
show_test_summary() {
    log_info "生成测试结果摘要..."
    
    # 查找最新的测试报告
    latest_report=$(find /tmp -name "persistence_test_report_*.json" 2>/dev/null | sort -r | head -1)
    
    if [ -n "$latest_report" ]; then
        log_success "找到测试报告: $(basename "$latest_report")"
        
        # 提取关键信息
        if command -v python3 &> /dev/null; then
            python3 << EOF
import json
try:
    with open('$latest_report', 'r') as f:
        report = json.load(f)
    
    print("\n" + "="*50)
    print("📊 测试结果摘要")
    print("="*50)
    
    # 部署结果
    deploy_results = report.get('deployment_results', {})
    deploy_success = sum(deploy_results.values())
    deploy_total = len(deploy_results)
    print(f"🚀 部署结果: {deploy_success}/{deploy_total} ({deploy_success/deploy_total*100:.1f}%)")
    
    # 验证结果
    verify_results = report.get('verification_results', {})
    verify_success = sum(verify_results.values())
    verify_total = len(verify_results)
    print(f"🔍 验证结果: {verify_success}/{verify_total} ({verify_success/verify_total*100:.1f}%)")
    
    # 详细结果
    print("\n📋 详细结果:")
    for mechanism, result in deploy_results.items():
        verify_result = verify_results.get(mechanism, False)
        deploy_status = "✅" if result else "❌"
        verify_status = "✅" if verify_result else "❌"
        print(f"  {mechanism}: 部署{deploy_status} 验证{verify_status}")
    
    print("="*50)
    
except Exception as e:
    print(f"解析报告失败: {e}")
EOF
        fi
    else
        log_warning "未找到测试报告文件"
    fi
}

# 清理测试环境
cleanup_test_environment() {
    if [ "$CLEANUP_AFTER_TEST" = true ]; then
        log_step "清理测试环境..."
        
        read -p "是否清理测试环境? (y/N): " cleanup_confirm
        if [[ $cleanup_confirm =~ ^[Yy]$ ]]; then
            python3 "$SCRIPT_DIR/ultimate_persistence_tester.py" --cleanup
            log_success "测试环境清理完成"
        else
            log_info "保留测试环境，稍后可手动清理"
        fi
    fi
}

# 显示后续操作建议
show_next_steps() {
    echo
    log_info "🎯 后续操作建议:"
    echo
    echo -e "${CYAN}1. 查看详细报告:${NC}"
    echo "   cat /tmp/persistence_test_report_*.md"
    echo
    echo -e "${CYAN}2. 重新运行测试:${NC}"
    echo "   bash $SCRIPT_DIR/one_click_persistence_test.sh"
    echo
    echo -e "${CYAN}3. 清理测试环境:${NC}"
    echo "   python3 $SCRIPT_DIR/ultimate_persistence_tester.py --cleanup"
    echo
    echo -e "${CYAN}4. 查看测试日志:${NC}"
    echo "   tail -f /tmp/persistence_test_*.log"
    echo
    echo -e "${CYAN}5. 系统安全加固:${NC}"
    echo "   - 更新系统: $PKG_UPDATE && $PKG_INSTALL updates"
    echo "   - 配置防火墙: systemctl enable firewalld && firewall-cmd --set-default-zone=drop"
    echo "   - 启用SELinux: setenforce 1"
    echo
}

# 错误处理
handle_error() {
    log_error "脚本执行过程中发生错误"
    log_info "正在执行清理操作..."
    
    # 基本清理
    rm -rf /tmp/persistence_test* 2>/dev/null || true
    
    log_info "清理完成，脚本退出"
    exit 1
}

# 主函数
main() {
    # 设置错误处理
    trap 'handle_error' ERR
    trap 'log_warning "脚本被中断"; exit 1' INT TERM
    
    # 显示横幅
    show_banner
    
    # 检查Root权限
    check_root
    
    # 检测系统
    detect_system
    
    # 系统初始化检查
    system_initialization_check
    
    # 安装依赖
    if [ "$INSTALL_DEPENDENCIES" = true ]; then
        install_dependencies
    fi
    
    # 配置系统环境
    configure_system
    
    # 安全检查
    security_check
    
    # 运行快速测试
    if [ "$AUTO_START_TEST" = true ]; then
        run_quick_test
    fi
    
    # 清理测试环境
    cleanup_test_environment
    
    # 显示后续操作建议
    show_next_steps
    
    log_success "🎉 重装系统后快速部署完成!"
    echo
    echo -e "${GREEN}感谢使用重装系统后快速部署脚本 v$VERSION${NC}"
    echo -e "${CYAN}会话ID: $SESSION_ID${NC}"
}

# 解析命令行参数
while [[ $# -gt 0 ]]; do
    case $1 in
        --no-install)
            INSTALL_DEPENDENCIES=false
            shift
            ;;
        --no-test)
            AUTO_START_TEST=false
            shift
            ;;
        --cleanup)
            CLEANUP_AFTER_TEST=true
            shift
            ;;
        --help|-h)
            cat << 'EOF'
重装系统后快速部署脚本 v2.0

用法: sudo bash quick_deploy_after_reinstall.sh [选项]

选项:
  --no-install    跳过依赖包安装
  --no-test       跳过自动测试
  --cleanup       测试后自动清理
  --help, -h      显示此帮助信息

示例:
  sudo bash quick_deploy_after_reinstall.sh
  sudo bash quick_deploy_after_reinstall.sh --no-install --cleanup

EOF
            exit 0
            ;;
        *)
            log_warning "未知参数: $1"
            shift
            ;;
    esac
done

# 脚本入口
if [[ "${BASH_SOURCE[0]}" == "${0}" ]]; then
    main "$@"
fi